/******************************************************************************\
    Pipe.hpp contains a class of windows pipe object.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#ifndef __PIPE_HPP
#define __PIPE_HPP

#include ".\Object.hpp"
#include ".\Handle.hpp"

class cPipe : public cHandle
{
public:
	bool Create( LPCTSTR name, DWORD open_mode, DWORD pipe_mode, DWORD max_instances, DWORD out_buffer_size, DWORD in_buffer_size, DWORD default_timeout, LPSECURITY_ATTRIBUTES security_attributes )
	{
		HANDLE pipe_handle = CreateNamedPipe( name, open_mode, pipe_mode, max_instances, out_buffer_size, in_buffer_size, default_timeout, security_attributes );
		if( pipe_handle == INVALID_HANDLE_VALUE )
			return false;
		cSubHandle *sub_handle;
		try
		{
			sub_handle = new cSubHandle( pipe_handle );
		}
		catch( ... )
		{
			return false;
		}
		SwitchToSubObject( sub_handle );
		return true;
	}
	bool Read( LPVOID buffer, DWORD number_of_bytes_to_read, LPDWORD number_of_bytes_read, LPOVERLAPPED overlapped )
	{
		if( GetSubObject() == NULL )
			return false;
		return ReadFile( GetSubObject()->Handle(), buffer, number_of_bytes_to_read, number_of_bytes_read, overlapped ) != FALSE;
	}
	bool Write( LPVOID buffer, DWORD number_of_bytes_to_write, LPDWORD number_of_bytes_written, LPOVERLAPPED overlapped )
	{
		if( GetSubObject() == NULL )
			return false;
		return WriteFile( GetSubObject()->Handle(), buffer, number_of_bytes_to_write, number_of_bytes_written, overlapped ) != FALSE;
	}
};

#endif